<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\common\builder\TableBuilder;
use app\common\builder\TableFront;
use app\common\model\User;
use Qiniu\Auth;
use think\App;
use think\facade\View;
use app\common\model\ProductCate;
use think\response\Json;
use app\common\model\ProductService;
use app\common\model\Business;

class Product extends Base
{

    //主键，默认为id
    protected $pk = 'id';

    //主模型
    protected $model = '\app\common\model\Product';

    //验证器
    protected $validate = 'Product';

    //关联模型
    protected $hasOne = ['cate1', 'cate2', 'cate3', 'business'];

    protected $append = ['examineStatusText'];

    public function index()
    {
        return $this->setTable('编辑', ['examine_status' => 2]);
    }

    public function examine()
    {
        return $this->setTable('审核', ['examine_del' => 0, 'is_del' => [0, 1]]);
    }

    public function setTable($action = '', $map = [])
    {
        //构建table
        $tableFront = TableFront::getInstance()
            ->addRow(['type' => 'checkbox', 'fixed' => 'left', 'field' => '', 'title' => '全选'])
            ->addRow(['field' => 'id', 'sort' => true, 'title' => 'ID', 'width' => 80, 'fixed' => 'left'])
            ->addRow(['title'   => '商家', 'width' => 200, 'fixed' => 'left',
                      'templet' => '<div>{{d.business.title}}</div>'])
            ->addRow(['field' => 'title', 'title' => '商品名称', 'width' => 200, 'fixed' => 'left'])
            ->addRow(['field' => 'icon', 'title' => '缩略图', 'width' => 90, 'templet' => '#iconTpl', 'fixed' => 'left'])
            ->addRow(['title'   => '商品分类', 'width' => 200,
                      'templet' => '<div>{{d.cate1.title}} - {{d.cate2.title}} - {{d.cate3.title}}</div>'])
            ->addRow(['field' => 'price', 'title' => '原价'])
            ->addRow(['field' => 'vip_price', 'title' => 'VIP价格'])
            ->addRow(['field' => 'currency', 'title' => '红包'])
            ->addRow(['field' => 'chain_bean', 'title' => '链豆'])
            ->addRow(['field' => 'love_bean', 'title' => '爱豆'])
            ->addRow(['field' => 'freight', 'title' => '运费'])
            ->addRow(['field' => 'stock', 'title' => '库存'])
            ->addRow(['field' => 'create_time', 'title' => '添加时间', 'width' => 150])
            ->addRow(['field' => 'update_time', 'title' => '更新时间', 'width' => 150]);
        $deleteBtn = ['edit' => ['width' => 1600, 'height' => 1200, 'title' => $action], 'delete'];
        if ($action == '编辑') {
            $tableFront->addRow(['field' => 'sort', 'title' => '排序', 'width' => 120, 'templet' => '#sort_sort'])
                ->addRow(['field' => 'status', 'title' => '状态', 'templet' => '#status', 'width' => 120, 'unresize' => true])
                ->addRow([ 'field' => 'pick', 'title' => '推荐', 'templet' => '#pick', 'width' => 120, 'unresize' => true])
                ->addRow(['field' => 'activity', 'title' => '限时活动', 'templet' => '#activity', 'width' => 120, 'unresize' => true])
                ->addRow(['field' => 'new', 'title' => '今日新品', 'templet' => '#new', 'width' => 120, 'unresize' => true]);
        } else {
            $tableFront->addRow(['field' => 'examineStatusText', 'title' => '审核状态'])
                ->addRow(['field' => 'examine_admin_name', 'title' => '审核人'])
                ->addRow(['field' => 'examine_time', 'title' => '审核时间', 'width' => 150]);
            $deleteBtn = ['edit' => ['width' => 1600, 'height' => 1200, 'title' => $action], 'delete' => ['url' => 'examineDelete']];
        }

        $tableFront->addRow(['fixed' => 'right', 'align' => 'center', 'toolbar' => '#productDemo', 'title' => '操作', 'width' => 150]);

        return TableBuilder::getInstance()
            ->addColumns($tableFront)
            ->addRightButtons($deleteBtn)
            ->addSwitchTool([
                ['name' => 'status', 'pk' => 'id', 'text' => '上架|下架'],
                ['name' => 'pick', 'pk' => 'id', 'text' => '开启|关闭'],
                ['name' => 'activity', 'pk' => 'id', 'text' => '开启|关闭'],
                ['name' => 'new', 'pk' => 'id', 'text' => '开启|关闭']
            ])
            ->setSearch($this->setSearch($action))
            ->addSortTool([['name' => 'sort', 'pk' => 'id', 'url' => url('update')->build()]])
            ->addExtraMap($map)
            ->addExtraHtml(['Product'])
            ->fetch();
    }

    public function setSearch($action)
    {
        $tableFront = TableFront::getInstance();
        $tableFront->setSearch(['business_id', '商家名称', 'input', '', '\app\common\model\Business', 'title,id'])
            ->setSearch(['title', '输入商品名称/描述', 'input', '', '', '', 'like'])
            ->setSearch(['cate_1', '商品专区', 'select', ProductCate::where(['pid' => 0, 'is_del' => 0])->column('title', 'id')])
            ->setSearch(['status', '上架状态', 'select', ['1' => '上架', '2' => '下架']])
        ;
        if ($action == '审核') {
            $tableFront->setSearch(['examine_status', '审核状态', 'select', [1 => '待审核', 2 => '已通过', 3 => '已驳回']]);
        }
        return $tableFront;
    }

    public function add($name = '', $tpl = 'product/add')
    {
        View::assign('business', Business::where(['is_del'=>0])->select());
        $data = $this->assignData();
        View::assign($data);
        return parent::add($name, $tpl);
    }

    public function edit($name = '', $id = '', $tpl = 'product/edit', $info = '')
    {
        $data = $this->assignData();
        $info = $this->model::find($id);
        $info->video_link_url = $info->video_link ? $data['domain'].$info->video_link : '';
        $info->content_videos_url = $info->content_videos ? $data['domain'].$info->content_videos : '';

        $info['service'] = $info['service'] ? explode(',', $info['service']) : '';
        $user = '';
        if($info->uid) $user = User::where('id', $info->uid)->value('concat_ws(" - ", nickname,code,mobile) as user');

        View::assign($data);
        View::assign('user', $user);
        return parent::edit($name, $id, $tpl, $info);
    }

    public function assignData()
    {
        $config = config('qiniu');
        // 构建鉴权对象
        $auth = new Auth($config['accessKey'], $config['secretKey']);
        $token = $auth->uploadToken($config['bucket']);

        return [
            'token' => $token,
            'domain' => $config['domain'],
            'cate' =>  ProductCate::getCate(),
            'service' => ProductService::where('is_del', 0)->select(),
        ];
    }

    public function getProduct()
    {
        try {
            $param = $this->request->get();
            $list = $this->model::whereLike('title', '%' . $param['val'] . '%')
                ->with(['business'])
                ->field('id,title,icon,business_id,price,vip_price')->select();
            return json(['code' => 0, 'data' => $list]);
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function save($param = [], $model = true): Json
    {
        return parent::save($param, $model); // TODO: Change the autogenerated stub
    }

    public function examineSave()
    {
        return json($this->model::examineSave($this->request->post(), $this->admin));
    }

    public function examineDelete()
    {
        try {
            $id = $this->request->post($this->pk);
            $model = $this->model::where($this->pk, $id)->find();
            $model->examine_del = 1;
            $model->save();
            \app\common\model\Logs::adds('删除【审核商品】记录ID【' . $id . '】');
            return json(['code' => 1, 'msg' => '已删除']);

        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    /**
     * 选择供应链会员
     * @return Json
     */
    public function selectUser(): Json
    {
        $param = $this->request->param();
        try{
            if ($this->request->isAjax()) {
                $user = User::whereLike('code|mobile|nickname', '%' . $param['val'] . '%')->field('id,code,mobile,nickname')->where('syn_level', '>=', 3)->where('is_del', 0)->select();
                return json(['code' => 0, 'data' => $user]);
            }
        }catch (\Exception $e){
            return json(['code' => -1, 'msg' => '请求失败']);
        }
    }

    public function addSave(): Json
    {
        try{
            $param = $this->request->post();
            $this->validate($param, 'Product');
            $business = Business::find($param['business_id']);
            return json($this->model::_saveSpec($param, $business, '已保存')); // TODO: Change the autogenerated stub
        } catch (\Exception $e) {
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }
    }

    public function getList($takeOver = true): Json
    {
        if($this->request->param('name') === 'Product_examine') $this->sort = 'update_time,desc';
        return parent::getList($takeOver); // TODO: Change the autogenerated stub
    }

}
